<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="分类" prop="category">
        <el-select v-model="queryParams.category" placeholder="请选择分类" clearable>
          <el-option
            v-for="dict in dict.type.admin_crop_varieties_category"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="名称" prop="cropName">
        <el-input
          v-model="queryParams.cropName"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="品种名称" prop="varietyName">
        <el-input
          v-model="queryParams.varietyName"
          placeholder="请输入品种名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="适宜种植状态" prop="plantingStatus">
        <el-select v-model="queryParams.plantingStatus" placeholder="请选择适宜种植状态" clearable>
          <el-option
            v-for="dict in dict.type.admin_planting_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="适宜种植" prop="plantingSeason">
        <el-select v-model="queryParams.plantingSeason" placeholder="请选择适宜种植" clearable>
          <el-option
            v-for="dict in dict.type.admin_planting_season"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['crop:crop:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['crop:crop:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['crop:crop:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['crop:crop:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="cropList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" :show-overflow-tooltip="true" />
      <el-table-column label="分类" align="center" prop="category" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.admin_crop_varieties_category" :value="scope.row.category"/>
        </template>
      </el-table-column>
      <el-table-column label="名称" align="center" prop="cropName" :show-overflow-tooltip="true" />
      <el-table-column label="品种名称" align="center" prop="varietyName" :show-overflow-tooltip="true" />
      <el-table-column label="适宜种植状态" align="center" prop="plantingStatus" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.admin_planting_status" :value="scope.row.plantingStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="适宜种植" align="center" prop="plantingSeason" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.admin_planting_season" :value="scope.row.plantingSeason"/>
        </template>
      </el-table-column>
      <el-table-column label="播种方式" align="center" prop="sowingMethod" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.admin_sowing_method" :value="scope.row.sowingMethod"/>
        </template>
      </el-table-column>
      <el-table-column label="是否是循环植物" align="center" prop="multiHarvest" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.admin_multi_harvest" :value="scope.row.multiHarvest"/>
        </template>
      </el-table-column>
      <el-table-column label="收获间隔天数" align="center" prop="harvestIntervalDays" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span v-if="scope.row.harvestIntervalDays">{{ scope.row.harvestIntervalDays }}</span>
          <span v-else style="color: #909399;">-</span>
        </template>
      </el-table-column>
      <el-table-column label="公历范围" align="center" prop="plantingDateRange" :show-overflow-tooltip="true" />
      <el-table-column label="农历范围" align="center" prop="plantingDateRangeLunar" :show-overflow-tooltip="true" />
      <el-table-column label="收获天数" align="center" prop="daysToHarvest" :show-overflow-tooltip="true" />
      <el-table-column label="收获天数范围" align="center" prop="maturityRangeDays" :show-overflow-tooltip="true" />
      <el-table-column label="最适温度" align="center" prop="optimalTemperature" :show-overflow-tooltip="true" />
      <el-table-column label="光照需求" align="center" prop="lightRequirement" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.admin_light_requirement" :value="scope.row.lightRequirement"/>
        </template>
      </el-table-column>
      <el-table-column label="水分要求" align="center" prop="waterRequirement" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.admin_water_requirement" :value="scope.row.waterRequirement"/>
        </template>
      </el-table-column>
      <el-table-column label="难易度" align="center" prop="growingDifficulty" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.admin_growing_difficulty" :value="scope.row.growingDifficulty"/>
        </template>
      </el-table-column>
      <el-table-column label="描述" align="center" prop="description" :show-overflow-tooltip="true" />
      <el-table-column label="风险提示" align="center" prop="riskWarnings" :show-overflow-tooltip="true" />
      <el-table-column label="封面图" align="center" prop="seedFrontImage" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.seedFrontImage" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="背面图" align="center" prop="seedBackImage" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.seedBackImage" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
      <el-table-column label="是否启用" align="center" prop="isActive" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.admin_is_active" :value="scope.row.isActive"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['crop:crop:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['crop:crop:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-link"
            @click="handleBindFruits(scope.row.id)"
            v-hasPermi="['crop:crop:list']"
          >绑定蔬果</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改后台-作物品种对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="分类" prop="category">
          <el-select v-model="form.category" placeholder="请选择分类">
            <el-option
              v-for="dict in dict.type.admin_crop_varieties_category"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="cropName">
          <el-input v-model="form.cropName" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="品种名称" prop="varietyName">
          <el-input v-model="form.varietyName" placeholder="请输入品种名称" />
        </el-form-item>
        <el-form-item label="适宜种植" prop="plantingSeason">
          <el-select v-model="form.plantingSeason" placeholder="请选择适宜种植" multiple collapse-tags>
            <el-option
              v-for="dict in dict.type.admin_planting_season"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="播种方式" prop="sowingMethod">
          <el-select v-model="form.sowingMethod" placeholder="请选择播种方式">
            <el-option
              v-for="dict in dict.type.admin_sowing_method"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否是循环植物" prop="multiHarvest">
          <el-select v-model="form.multiHarvest" placeholder="请选择是否是循环植物">
            <el-option
              v-for="dict in dict.type.admin_multi_harvest"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="收获间隔天数" prop="harvestIntervalDays" v-if="form.multiHarvest === 1">
          <el-input v-model="form.harvestIntervalDays" placeholder="请输入收获间隔天数" type="number" />
        </el-form-item>
        <el-form-item label="公历(范围)" prop="plantingDateRange">
          <el-input v-model="form.plantingDateRange" placeholder="请输入公历" />
        </el-form-item>
        <el-form-item label="农历(范围)" prop="plantingDateRangeLunar">
          <el-input v-model="form.plantingDateRangeLunar" placeholder="请输入农历" />
        </el-form-item>
        <el-form-item label="收获天数" prop="daysToHarvest">
          <el-input v-model="form.daysToHarvest" placeholder="请输入收获天数" />
        </el-form-item>
        <el-form-item label="收获天数(范围)" prop="maturityRangeDays">
          <el-input v-model="form.maturityRangeDays" placeholder="请输入收获天数" />
        </el-form-item>
        <el-form-item label="最适温度" prop="optimalTemperature">
          <el-input v-model="form.optimalTemperature" placeholder="请输入最适温度" />
        </el-form-item>
        <el-form-item label="光照需求" prop="lightRequirement">
          <el-select v-model="form.lightRequirement" placeholder="请选择光照需求">
            <el-option
              v-for="dict in dict.type.admin_light_requirement"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="水分要求" prop="waterRequirement">
          <el-select v-model="form.waterRequirement" placeholder="请选择水分要求">
            <el-option
              v-for="dict in dict.type.admin_water_requirement"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="难易度" prop="growingDifficulty">
          <el-select v-model="form.growingDifficulty" placeholder="请选择难易度">
            <el-option
              v-for="dict in dict.type.admin_growing_difficulty"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="风险提示" prop="riskWarnings">
          <el-input v-model="form.riskWarnings" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="封面图" prop="seedFrontImage">
          <image-upload v-model="form.seedFrontImage"/>
        </el-form-item>
        <el-form-item label="背面图" prop="seedBackImage">
          <image-upload v-model="form.seedBackImage"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="是否启用" prop="isActive">
          <el-select v-model="form.isActive" placeholder="请选择是否启用">
            <el-option
              v-for="dict in dict.type.admin_is_active"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    
    <!-- 绑定蔬果对话框 -->
    <el-dialog
      :title="'绑定蔬果'"
      :visible.sync="bindFruitsDialog"
      width="600px"
      append-to-body
    >
      <el-form ref="bindFruitsForm" :model="{}" label-width="120px">
        <el-form-item label="果蔬品种列表">
          <el-checkbox-group v-model="selectedCropIds" :disabled="bindFruitsLoading">
            <el-checkbox
              v-for="crop in allCropList"
              :key="crop.id"
              :label="crop.id"
              style="display: block; margin-bottom: 10px;"
            >
              <span style="margin-left: 5px;">{{ crop.category }} - {{ crop.cropName }} - {{ crop.varietyName }}</span>
            </el-checkbox>
          </el-checkbox-group>
          <div v-if="bindFruitsLoading" style="text-align: center; padding: 20px;">
            <el-loading-spinner size="small"></el-loading-spinner>
            <span style="margin-left: 10px;">加载中...</span>
          </div>
          <div v-else-if="allCropList.length === 0" style="text-align: center; padding: 20px;">
            暂无可用的果蔬品种
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelBindFruits">取 消</el-button>
        <el-button type="primary" @click="submitBindFruits" :loading="bindFruitsLoading">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCrop, getCrop, delCrop, addCrop, updateCrop } from "@/api/crop/crop"
import { listAllCrop, addPlantToPlot } from "@/api/plot/plot"

export default {
  name: "Crop",
  dicts: ['admin_water_requirement', 'admin_crop_varieties_category', 'admin_light_requirement', 'admin_growing_difficulty', 'admin_planting_season', 'admin_sowing_method', 'admin_is_active', 'admin_planting_status', 'admin_multi_harvest'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 绑定蔬果对话框
      bindFruitsDialog: false,
      // 选中的菜园ID
      currentPlotId: null,
      // 果蔬列表
      allCropList: [],
      // 选中的果蔬ID列表
      selectedCropIds: [],
      // 绑定蔬果加载状态
      bindFruitsLoading: false,
      // 总条数
      total: 0,
      // 后台-作物品种表格数据
      cropList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        category: null,
        cropName: null,
        varietyName: null,
        plantingSeason: null,
        plantingStatus: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        category: [
          { required: true, message: "分类不能为空", trigger: "change" }
        ],
        cropName: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        varietyName: [
          { required: true, message: "品种名称不能为空", trigger: "blur" }
        ],
        plantingSeason: [
          { required: true, message: "适宜种植不能为空", trigger: "change" }
        ],
        sowingMethod: [
          { required: true, message: "播种方式不能为空", trigger: "change" }
        ],
        plantingDateRange: [
          { required: true, message: "公历不能为空", trigger: "blur" }
        ],
        multiHarvest: [
          { required: true, message: "是否是循环植物不能为空", trigger: "change" }
        ],
        harvestIntervalDays: [
          { required: true, message: "收获间隔天数不能为空", trigger: "blur", validator: (rule, value, callback) => {
              if (this.form.multiHarvest === 1 && !value) {
                callback(new Error('收获间隔天数不能为空'));
              } else {
                callback();
              }
            } 
          }
        ],
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询后台-作物品种列表 */
    getList() {
      this.loading = true
      listCrop(this.queryParams).then(response => {
        this.cropList = response.rows
        this.total = response.total
        this.loading = false
        // 查看返回数据中是否包含plantingStatus字段
        console.log('返回数据中的plantingStatus:', response.rows.map(item => item.plantingStatus))
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    
    // 打开绑定蔬果对话框
    handleBindFruits(plotId) {
      this.currentPlotId = plotId;
      this.selectedCropIds = [];
      this.bindFruitsDialog = true;
      this.getAllCropList();
    },
    
    // 获取所有果蔬列表
    getAllCropList() {
      this.bindFruitsLoading = true;
      listAllCrop().then(response => {
        this.allCropList = response.data;
        this.bindFruitsLoading = false;
      }).catch(error => {
        console.error('获取果蔬列表失败:', error);
        this.bindFruitsLoading = false;
        this.$message.error('获取果蔬列表失败');
      });
    },
    
    // 提交绑定蔬果
    submitBindFruits() {
      if (this.selectedCropIds.length === 0) {
        this.$message.warning('请至少选择一个果蔬品种');
        return;
      }
      
      this.bindFruitsLoading = true;
      const params = {
        plotId: this.currentPlotId,
        cropIds: this.selectedCropIds
      };
      
      addPlantToPlot(params).then(response => {
        if (response.code === 200) {
          this.$message.success('绑定成功');
          this.cancelBindFruits();
        } else {
          this.$message.error(response.msg || '绑定失败');
        }
        this.bindFruitsLoading = false;
      }).catch(error => {
        console.error('绑定蔬果失败:', error);
        this.bindFruitsLoading = false;
        this.$message.error('绑定蔬果失败');
      });
    },
    
    // 取消绑定蔬果
    cancelBindFruits() {
      this.bindFruitsDialog = false;
      this.selectedCropIds = [];
      this.currentPlotId = null;
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        category: null,
        cropName: null,
        varietyName: null,
        plantingSeason: null,
        sowingMethod: null,
        plantingDateRange: null,
        plantingDateRangeLunar: null,
        daysToHarvest: null,
        maturityRangeDays: null,
        optimalTemperature: null,
        lightRequirement: null,
        waterRequirement: null,
        growingDifficulty: null,
        description: null,
        riskWarnings: null,
        seedFrontImage: null,
        seedBackImage: null,
        remark: null,
        createdAt: null,
        createdBy: null,
        updatedAt: null,
        updatedBy: null,
        isActive: null,
        isDeleted: null,
        deletedAt: null,
        tenantId: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加后台-作物品种"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getCrop(id).then(response => {
        this.form = response.data
        // 如果plantingSeason是字符串，则按逗号分割成数组
        if (this.form.plantingSeason && typeof this.form.plantingSeason === 'string') {
          this.form.plantingSeason = this.form.plantingSeason.split(',')
        }
        this.open = true
        this.title = "修改后台-作物品种"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 深拷贝表单对象，避免修改原始数据
          const formData = JSON.parse(JSON.stringify(this.form))
          // 如果plantingSeason是数组，则用逗号拼接成字符串
          if (Array.isArray(formData.plantingSeason)) {
            formData.plantingSeason = formData.plantingSeason.join(',')
          }
          
          if (this.form.id != null) {
            updateCrop(formData).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addCrop(formData).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除后台-作物品种编号为"' + ids + '"的数据项？').then(function() {
        return delCrop(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('crop/crop/export', {
        ...this.queryParams
      }, `crop_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
